package org.ling.xuan.util;

import cn.hutool.core.codec.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class HttpDownLoadUtil {
    /**
     * 下载文件
     *
     * @param fileUrl             文件url
     * @param destinationFilePath 目标文件路径
     * @throws IOException ioexception
     */
    public static void svnDownLoad(String fileUrl, String destinationFilePath, String userName, String pwd) throws IOException {
        CloseableHttpClient httpClient = createInsecureHttpClient();
        HttpGet httpGet = new HttpGet(fileUrl.trim());
        httpGet.setHeader("Authorization", "Basic " + Base64.encode(userName + ":" + pwd, StandardCharsets.UTF_8));
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try (FileOutputStream outputStream = new FileOutputStream(destinationFilePath)) {
                        entity.writeTo(outputStream);
                    }
                }
            } else {
                throw new IOException("下载失败：状态码：" + response.getStatusLine().getStatusCode());
            }
        } finally {
            httpClient.close();
        }
    }

    public static CloseableHttpClient createInsecureHttpClient() {
        try {
            // Ignore SSL certificate and hostname verification
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true).build();
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).build();
            return HttpClients.custom()
                    .setSslcontext(sslContext)
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .setDefaultRequestConfig(requestConfig)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static boolean exist(String fileUrl, String userName, String pwd) throws IOException {
        CloseableHttpClient httpClient = createInsecureHttpClient();
        HttpHead httpOptions = new HttpHead(fileUrl.trim());
        httpOptions.setHeader("Authorization", "Basic " + Base64.encode(userName + ":" + pwd, StandardCharsets.UTF_8));
        httpOptions.setHeader("Connection", "close");
        try {
            HttpResponse response = httpClient.execute(httpOptions);
            int code = response.getStatusLine().getStatusCode();
            if (code >= 200 && code < 300) {
                return true;
            } else if(code==404){
                return false;
            }else{
                throw new RuntimeException("文件访问失败,请检查路径或者用户名密码");
            }
        } finally {
            httpClient.close();
        }
    }

}
